package com.dongdongkeji.base.api;

import android.content.Context;
import android.content.DialogInterface;

import com.dongdongkeji.base.widget.progress.ProgressDialogHandler;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Author: ChenJing
 * Date: 2017-06-19 下午 4:21
 * Version: 1.0
 * Desc: 带加载提示框的网络请求回调
 */

public abstract class ProgressObserver<T> extends BaseObserver<T> implements DialogInterface.OnCancelListener {

    private Disposable disposable;
    private ProgressDialogHandler dialogHandler;

    public ProgressObserver(Context context, CompositeDisposable disposables) {
        super(context, disposables);
        this.dialogHandler = new ProgressDialogHandler(context, this, true);
    }

    @Override
    public void onSubscribe(Disposable d) {
        super.onSubscribe(d);
        disposable = d;
        showProgress();
    }

    @Override
    public void onComplete() {
        super.onComplete();
        hideProgress();
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        hideProgress();
    }

    @Override
    public void onCancel(DialogInterface dialogInterface) {
        if (null != disposable){
            disposable.dispose();
            disposables.remove(disposable);
        }
        onCancel();
    }

    /**
     * 取消请求
     *
     * 实现类可重写此方法，以做取消网络请求后的响应处理
     */
    public void onCancel(){}

    /**
     * 通知Handler显示加载框
     */
    private void showProgress(){
        if (dialogHandler != null){
            dialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    /**
     * 通知Handler隐藏加载框
     */
    private void hideProgress(){
        if (null != dialogHandler){
            dialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
        }
    }
}
